package cn.xy.commons.validator;

import cn.hutool.core.util.ObjectUtil;
import lombok.SneakyThrows;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 枚举校验
 *
 * @author HuangYuHan
 */
@Documented
@Constraint(
        validatedBy = {EnumValidator.EnumConstraintValidator.class}
)
@Target(value = {ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EnumValidator {

    /**
     * 枚举
     */
    Class<? extends VerifiedEnum> clazz();

    /**
     * 是否必须的(默认false)
     */
    boolean required() default false;

    /**
     * 错误信息
     */
    String message() default "传入值不存在其枚举";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class EnumConstraintValidator implements ConstraintValidator<EnumValidator, Object> {
        VerifiedEnum[] enumConstants;
        boolean required;

        @SneakyThrows
        @Override
        public void initialize(EnumValidator constraintAnnotation) {
            enumConstants = constraintAnnotation.clazz().getEnumConstants();
            required = constraintAnnotation.required();
        }

        @Override
        public boolean isValid(Object o, ConstraintValidatorContext context) {
            if (o == null) {
                return true;
            }
            for (VerifiedEnum verifiedEnum : enumConstants) {
                if (ObjectUtil.equals(verifiedEnum.getVerifiedValue(), o)) {
                    return true;
                }
            }
            return false;
        }
    }
}